import React, { useImperativeHandle, useRef, useState } from 'react';
import { intl, nanoid10 } from "@/utils";
import { DataGrid, Popup } from 'devextreme-react';
import { CpasIcon, LayoutB } from '~/public/cpas-ui';
import { Column, Editing, Lookup, Paging, Selection } from 'devextreme-react/data-grid';
import './index.less';

import { conditionStatesData } from '../tableColumnData';
import { AdvQueryParam, DbFieldInfo, SampleTable } from '@/pages/auditSampling/typing';
import { isNumeric } from '@/utils/pub';
import { msgError } from '@/utils/msg';
import { consts } from '@/pages/auditSampling/consts';

const AdvancedQueryPupop = React.forwardRef((props: any, ref: any) => {
    const [visible, setVisible] = useState<boolean>(false);
    const popupRef = useRef<any>(null);
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const dataGridRef = useRef<any>(null);

    const diaParams = useRef<any>(null);

    const [conditionsData, setConditionsData] = useState<any[]>([]);

    const [srcConditionsColumns, setSrcConditionColumns] = useState<any[]>([]);



    const onCancel = () => {
        setConditionsData([]);
        setVisible(false);
    }
    const onOk = async () => {
        dataGridRef.current.instance.saveEditData().then(() => {

            //转换为字符串
            conditionsData.forEach(item => item.rowConditionsData = item.rowConditionsData.toString())
            for (let i = 0; i < conditionsData.length; i++) {
                const condition = conditionsData[i];
                const sourceField = srcConditionsColumns.find(item => item.keyDataString == condition.keyString);
                if (sourceField && sourceField.isNum) {
                    const fieldInfo: DbFieldInfo = sourceField.fieldInfo;
                    if (condition.rowConditionsData) {//数字列替换,
                        condition.rowConditionsData = (condition.rowConditionsData.toString()).replace(',', '')
                    }
                    if (!condition.rowConditionsData) {
                        return msgError(`第 ${i + 1} 行, 【${sourceField.conditionsName}】不能为空且必须是数字!`);
                    }
                    if (!isNumeric(condition.rowConditionsData)) {
                        return msgError(`第 ${i + 1} 行,【${sourceField.conditionsName}】 必须是数字!`);
                    }
                    // 判断是否是整数
                    if (['int', 'bigint', 'bit'].includes(fieldInfo.dataType)
                        && condition.rowConditionsData.includes('.')) {//小数
                        return msgError(`第 ${i + 1} 行,【${sourceField.conditionsName}】 不能是小数,必须是整数!`);
                    }
                }

            }
            console.log(conditionsData, '@@@');

            //如果 有新条件或老的条件，就调用回调
            if (conditionsData.length || (diaParams.current?.conditionsData || []).length) {
                diaParams.current?.okCallback(conditionsData);
            }
            onCancel();
        })

    }



    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            diaParams.current = params;
            const tableFieldNameInfo: DbFieldInfo[] = params.tableFieldNameInfo;
            const sampleTable: SampleTable = params.sampleTable;
            const srcConditionsColumns: AdvQueryParam[] = sampleTable.sampleAllFieldsArray
                .filter(item => item.visible).map(item => ({
                    keyDataString: item.fieldName,
                    conditionsName: item.fieldTitle,
                    sqlType: item.isNum ? 'number' : 'string',
                    isNum: item.isNum,
                    fieldInfo: tableFieldNameInfo.find(item2 => item2.fieldName == item.fieldName)
                }));

            //是否包含结转凭证
            if (sampleTable.isVoucher) {
                srcConditionsColumns.push({
                    keyDataString: 'IdentifyJZ',
                    conditionsName: '是否包含结转凭证',
                    sqlType: 'string',
                    isNum: 0,
                    fieldInfo: tableFieldNameInfo.find(item2 => item2.fieldName == 'IdentifyJZ')
                });
            }

            setSrcConditionColumns(srcConditionsColumns);
            setConditionsData([...params.conditionsData ?? []]);
            setVisible(true);
        },
    }));

    const changeSaveData = (newData: any) => {
        if (!newData) return;
        const tempID = newData.guid;
        // 修改更改的值
        setConditionsData((oldData: any) => {
            let newData = [...oldData];
            newData.forEach(item => {
                if (item.guid === tempID) {
                    return newData;
                }
                return item;
            });
            return newData;
        });
    }

    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            console.log(data, '@@@');

            changeSaveData(data);
        }
    }

    function leftContainer() {
        return (
            <div style={{ marginRight: "15px", height: "100%" }} >
                <div>查询条件</div>
                <DataGrid
                    className='devHeadersCenter PaperDevSortableGrid advancedQueryDataGrid'
                    ref={dataGridRef}
                    dataSource={conditionsData}
                    keyExpr="guid"
                    height=" calc(100% - 20px) "
                    showBorders={true}
                    showRowLines={true}
                    showColumnLines={true}
                    rowAlternationEnabled={true}

                    onCellClick={(e) => {
                        const { rowType, data, columnIndex } = e;
                        if (rowType === 'data') {
                            // console.log(data, e, columnIndex, '@@@');
                            if (columnIndex === 0) {
                                setConditionsData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.andorStr === '1') {
                                                item.andorStr = '0';
                                            } else {
                                                item.andorStr = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            } else if (columnIndex === 1) {
                                setConditionsData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.leftParenthesis === '1') {
                                                item.leftParenthesis = '0';
                                            } else {
                                                item.leftParenthesis = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            } else if (columnIndex === 5) {
                                setConditionsData((oldData: any) => {
                                    let newData = [...oldData];
                                    newData.forEach(item => {
                                        if (data.guid === item.guid) {
                                            if (item.rightParenthesis === '1') {
                                                item.rightParenthesis = '0';
                                            } else {
                                                item.rightParenthesis = '1';
                                            }
                                        }
                                    });
                                    return newData;
                                })
                            }
                        }

                    }}
                    allowHeaderFiltering={false}
                    allowSorting={false}
                    onSaved={SavedData}

                    editing={{ mode: 'cell', allowDeleting: true, allowUpdating: true }}

                    onEditorPreparing={(e) => {
                        //值  值
                        if (e.dataField == 'rowConditionsData') {
                            //是否结转凭证
                            const fieldName = e.row?.data?.keyString;
                            const columnInfo = srcConditionsColumns.find(item => item.keyDataString == fieldName)

                            if (fieldName == "IdentifyJZ") {
                                e.editorName = 'dxSelectBox'
                                e.editorOptions = {
                                    valueExpr: 'id',
                                    displayExpr: 'text',
                                    dataSource: consts.AcYesNoOnlyList,
                                    onValueChanged: (e1: any) => {
                                        e.setValue(e1.value)

                                    }
                                }
                            }
                            //数字输入框
                            else if (columnInfo?.isNum) {
                                e.editorName = 'dxNumberBox'
                            }

                        }
                        else if (e.dataField == 'StateID') {
                            const fieldName = e.row?.data?.keyString;
                            const columnInfo = srcConditionsColumns.find(item => item.keyDataString == fieldName)
                            //是否标记结转时,不能选择
                            if (fieldName == "IdentifyJZ") {
                                e.editorName = 'dxTextBox'
                                e.editorOptions = {
                                    value: '不可改',
                                    disabled: true,
                                }
                            }

                        }
                    }
                    }


                >
                    <Paging enabled={false} />
                    <Editing
                        mode="cell"
                        allowUpdating={true}
                        allowAdding={false}
                        allowDeleting={false} />
                    <Column
                        caption="或/且"
                        dataField="andorStr"
                        allowEditing={false}
                        width={60}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.andorStr === "0") {
                                aaaa = <CpasIcon type={'icon-huo'} fontSize={16} />;
                            } else if (data.andorStr === "1") {
                                aaaa = <CpasIcon type={'icon-Remove-svg'} fontSize={16} />;
                            }
                            return <div style={{ width: '100%', height: '24px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'red', cursor: 'pointer' }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                    <Column
                        caption="左括弧"
                        dataField="leftParenthesis"
                        allowEditing={false}
                        width={70}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.leftParenthesis === "1") {
                                aaaa = '（';
                            } else {
                                aaaa = ' ';
                            }
                            return <div style={{
                                width: '100%', height: '24px',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                color: 'red', cursor: 'pointer', fontWeight: 'bold'
                            }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                    <Column
                        caption="字段名称"
                        dataField="conditionsName"
                        width={120}
                        allowEditing={false}
                    />
                    <Column dataField="StateID" caption="条件" width={100} editorOptions={{ width: 150 }}>
                        <Lookup dataSource={conditionStatesData} valueExpr="StateID" displayExpr="conditionName" />
                    </Column>
                    <Column
                        caption="值"
                        dataField="rowConditionsData"
                    />
                    <Column
                        caption="右括弧"
                        dataField="rightParenthesis"
                        width={70}
                        allowEditing={false}
                        cellRender={(e) => {
                            const { data } = e;
                            let aaaa: any = null;
                            if (data.rightParenthesis === "1") {
                                aaaa = '）';
                            } else {
                                aaaa = ' ';
                            }
                            return <div style={{
                                width: '100%', height: '24px',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                                color: 'red', cursor: 'pointer', fontWeight: 'bold'
                            }}>
                                {aaaa}
                            </div>;
                        }}
                    />
                </DataGrid>
            </div >
        );
    }

    function rightContainer() {
        return (
            <div style={{ marginLeft: "15px", height: "100%" }}>
                <div>双击增加条件</div>
                <DataGrid
                    dataSource={srcConditionsColumns}
                    keyExpr="keyDataString"
                    showBorders={true}
                    showColumnHeaders={false}
                    height="calc(100% - 20px)"
                    onRowDblClick={(e: any) => {
                        const { data } = e;
                        setConditionsData((oldData: any) => {
                            let newData = [...oldData];
                            let stateID = 0;

                            let keyDataString: string = data.keyDataString || '';
                            let conditionsName: string = data.conditionsName || '';
                            if (keyDataString === 'ZY') {
                                stateID = 7;//包含
                            } else if (conditionsName.includes('科目')) {
                                stateID = 9//左包含
                            } else if (data.fieldInfo?.dataType.includes('varchar')) {//字符串
                                stateID = 7;//包含
                            }
                            newData.push({
                                guid: nanoid10(),
                                andorStr: '1',
                                leftParenthesis: '0',
                                conditionsName: data.conditionsName,
                                StateID: stateID,
                                rowConditionsData: keyDataString == 'IdentifyJZ' ? consts.no : '',
                                rightParenthesis: '0',
                                keyString: data.keyDataString,
                                sqlType: data.sqlType
                            })
                            return newData;
                        });
                    }}
                    paging={{ enabled: false }}
                    showRowLines={false}
                    searchPanel={{ visible: true, width: 250, placeholder: '输入关键字' }}
                >
                    <Selection mode="single" />
                    <Column
                        dataField="conditionsName"
                    />
                </DataGrid>
            </div >
        );
    }




    return (
        <>
            <Popup
                ref={popupRef}
                visible={visible}
                title='查询条件构造器'
                width={1000}
                height={700}
                // dragOutsideBoundary={true}
                // resizeEnabled={true}
                onHiding={() => { onCancel() }}

                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            // disabled: conditionsData.length == 0,
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },

                ]}
                contentRender={() => (
                    <div style={{ height: '575px', width: '100%', overflow: 'hidden' }} >
                        <LayoutB
                            rowSize={["650px", "700px", "750px"]}
                            leftSlot={leftContainer()}
                            rightSlot={rightContainer()}
                        />
                    </div>
                )}
            />
        </>
    );
});

export default AdvancedQueryPupop;
